package com.sghj.utils;

import com.google.gson.Gson;
import com.google.gson.JsonObject;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.client.RestTemplate;

/**
 * @author zk
 * @version 1.0
 * @date 2023-11-15 10:06
 * @description
 */


public class RestApiClient {

    private HttpHeaders headers;
    private RestTemplate restTemplate;
    private Gson gson;

    public RestApiClient(String token) {
        headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        headers.set("Authorization", "Bearer " + token);
        restTemplate = new RestTemplate();
        gson = new Gson();
    }

    public JsonObject postForObject(String url, Object requestBody) {
        HttpEntity<Object> requestEntity = new HttpEntity<>(requestBody, headers);
        ResponseEntity<String> responseEntity = restTemplate.postForEntity(url, requestEntity, String.class);
        String responseBody = responseEntity.getBody();
        return gson.fromJson(responseBody, JsonObject.class);
    }
}
